// pages/my/my.js
const util = require('../../utils/util')
// 初始化云数据库环境
let db = wx.cloud.database({
  env: 'junsheng0108-9gsv99le6b9d0ec9'
});
let user = db.collection('db_user');
let signin = db.collection('db_signIn')
let job = db.collection('db_job');
let undone = db.collection('db_undone')
let flag = db.collection('db_flag')
let finish = db.collection('db_finish')
// 连接数据表
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 记录用户数据对象
    userInfo: {},
    // 设置false,需要询问用户是否允许获取头像和昵称
    canIUseGetUserProfile: true,
    // 判断用户是否获取了用户信息
    hasUserInfo: false,
    // 定义数组 记录签到信息
    signinList: [],
    // 输入框的状态
    isEdit: false,
    all: 0,
    finish: 0,
    undone: 0,
    isShow: false
  },

  // 签到表，插入数据
  addSignin(user_id, user_nickname, signin_id, signin_create_time) {
    return new Promise((resolve, reject) => {
      signin.add({
          data: {
            user_id,
            user_nickname,
            signin_id,
            signin_create_time
          }
        })
        .then(content => {
          resolve(content)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 点击设置签到
  async addSigninFunc() {
    let openid = wx.getStorageSync('openid');
    if (openid) {
      let that = this
      // 获取昵称
      let user_nickName = wx.getStorageSync('nickName');
      // 获取用户身份
      let openid = wx.getStorageSync('openid');
      // 产生一个随机的字符串
      let signin_id = Math.random().toString().slice(2);
      // 记录签到的时间
      let dt = new Date();
      let create_time = util.formatTime(dt).slice(0, 10)
      let signin_create_time = util.formatTime(dt);
    
      let sign = this.data.signinList;
      if (sign.length == 0) {
        await this.addSignin(openid, user_nickName, signin_id, signin_create_time)
          .then(content => {
            console.log('1.0', content);
            wx.showToast({
              title: '签到成功',
              icon: 'success'
            })
            that.listSignin()
    
          })
          .catch(error => {
            console.log('1.1', error);
          })
      } else {
          let length = this.data.signinList.length
          if (sign[length - 1].signin_create_time.slice(0, 10) == create_time) {
            wx.showToast({
              title: '今天已签到',
              icon: 'error'
            })
          } else {
            await this.addSignin(openid, user_nickName, signin_id, signin_create_time)
              .then(content => {
                console.log('1.0', content);
                wx.showToast({
                  title: '签到成功',
                  icon: 'success'
                })
                that.listSignin()
              })
              .catch(error => {
                console.log('1.1', error);
              })
          }
        
      }
      this.listSignin()
      console.log('11', sign);
    } else {
      wx.showToast({
        title: '还没登录呢',
        icon: 'error'
      })
    }
  },

  // 签到表，查询数据（所有数据）
  async listSignin() {
    // 定义变量 记录签到表的总数量
    let count = 0

    // 统计总数量
    await signin.where({
        _openid: "oKjix5Rb5Y38DQqR5NsupdSpj37M"
      }).count()
      .then(content => {
        console.log(content)
        let {
          total,
          errMsg
        } = content;
        if (errMsg == "collection.count:ok") {
          count = total;
        }
      })

    // 定义空数组记录所有签到数据
    let arr = [];
    // 循环签到表
    for (let i = 0; i < count; i += 5) {
      await signin.skip(i).limit(5).where({
        _openid: "oKjix5Rb5Y38DQqR5NsupdSpj37M"
      }).get().then(content => {
        console.log(content)
        let {
          errMsg,
          data
        } = content;
        if (errMsg == "collection.get:ok") {
          // 合并数组
          arr = arr.concat(data);
        }
      })
    }
    this.setData({
      signinList: arr
    })
    // 隐藏加载提示
    wx.hideLoading();
  },

  modifyNickNameFunc() {
    // 可编辑状态
    this.setData({
      isEdit: false
    })
  },

  saveNickNameFunc() {

    // 不可编辑状态
    this.setData({
      isEdit: true
    })
  },


  // 获取用户信息（昵称，头像）
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，
    //开发者每次通过该接口获取用户个人信息均需用户确认，
    //开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息',
      // 声明获取用户个人信息后的用途，
      //后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        // 解构赋值 获取用户昵称和头像
        let {
          userInfo: {
            nickName,
            avatarUrl
          }
        } = res;
        // 调用云函数登记用户信息
        this.getUserInfoFunc(nickName, avatarUrl)
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        })
      }
    })
  },

  // 编写方法 获取用户信息
  getUserInfoFunc(nickName, avatarUrl) {
    // 获取日期对象
    let dt = new Date()
    // 调用云函数
    wx.cloud.callFunction({
      name: 'user',
      data: {
        user_create_time: util.formatTime(dt),
        nickName,
        avatarUrl
      },
      success(content) {
        console.log(content);
        let {
          errMsg,
          result
        } = content;
        if (errMsg == 'cloud.callFunction:ok') {
          console.log(result);
          if (result.code == '200') {
            let {
              userInfo: {
                avatarUrl,
                nickName,
                openid,
                user_create_time
              }
            } = result
            // 缓存数据
            wx.setStorageSync('avatarUrl', avatarUrl);
            wx.setStorageSync('nickName', nickName);
            wx.setStorageSync('openid', openid);
            wx.setStorageSync('user_create_time', user_create_time);
            wx.setStorageSync('userinfo', JSON.stringify(result.userInfo))
            wx.setStorageSync('isHas', 1)
            // 调用云数据库API
            user.add({
              data: {
                user_id: openid,
                // _openid: openid,
                user_nickname: nickName,
                user_create_time: user_create_time,
                user_avatar: avatarUrl
              }
            })
          }
        } else {
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'error'
          })
        }
      },
      fail(error) {
        console.log("请求失败", error);
      }
    })
  },

  //点击跳转旗帜
  getJumpFlag() {
    let openid = wx.getStorageSync('openid');
    if (openid) {
      wx.navigateTo({
        url: '../flag/flag',
      })
    } else {
      wx.showToast({
        title: '还没登录呢',
        icon: 'error'
      })
    }
  },

  //点击退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '是否退出登录',
      complete: (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          wx.clearStorageSync('openid')
          this.setData({
            hasUserInfo: false
          })
          this.userCon()
          wx.showToast({
            title: '退出登录成功',
            icon: 'success'
          })
        }
      }
    })
  },
  // 点击跳转个人资料
  jumpPersonal() {
    let openid = wx.getStorageSync('openid');
    if (openid) {
      wx.navigateTo({
        url: '../personal/personal',
      })
    } else {
      wx.showToast({
        title: '还没登录呢',
        icon: 'error'
      })}
  },
  jumpAll() {
    let openid = wx.getStorageSync('openid');
    if (openid) {
      wx.navigateTo({
        url: '../allwork/allwork',
      })
    } else {
      wx.showToast({
        title: '还没登录呢',
        icon: 'error'
      })
    }

  },
  jumpFinish() {
    let openid = wx.getStorageSync('openid');
    if (openid) {
      wx.navigateTo({
        url: '../finish/finish',
      })
    } else {
      wx.showToast({
        title: '还没登录呢',
        icon: 'error'
      })
    }
  },
  jumpUndone() {
    let openid = wx.getStorageSync('openid');
    if (openid) {
      wx.navigateTo({
        url: '../undone/undone',
      })
    } else {
      wx.showToast({
        title: '还没登录呢',
        icon: 'error'
      })
    }
  },




  async userCon() {
    await user.get().then(content => {
      console.log(content);
    }).catch(error => {
      console.log(error);
    })
  },

  // 渲染已完成总数值
  async finishTotal() {
    await finish.get()
      .then(content => {
        let {
          data,
          errMsg
        } = content;
        if (errMsg == "collection.get:ok") {
          this.setData({
            finish: data.length,
          })
        }
      })
  },
  // 渲染未完成总数值
  async undoneTotal() {
    await undone.get()
      .then(content => {
        let {
          data,
          errMsg
        } = content;
        if (errMsg == "collection.get:ok") {
          this.setData({
            undone: data.length,
          })
        }
      })
  },
  // 渲染列表总数值
  async getJobList() {
    await job.get()
      .then(content => {
        console.log(content)
        let {
          data,
          errMsg
        } = content;
        if (errMsg == "collection.get:ok") {
          this.setData({
            all: data.length,
          })
        }
      })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let isHas = wx.getStorageSync('isHas')
    if (isHas) {
      // 获取本地存储的数据
      let usrinfo = JSON.parse(wx.getStorageSync('userinfo'))
      this.setData({
        canIUseGetUserProfile: false,
        hasUserInfo: true,
        userInfo: usrinfo
      })
    } else {
      this.setData({
        canIUseGetUserProfile: true
      })
      // 查询用户所有数据
      user.where({
        _openid: 'oKjix5Rb5Y38DQqR5NsupdSpj37M'
      }).get().then(content => {
        console.log('用户列表', content);
      }).catch(error => {
        console.log(error);
      })
    }
    //初始化，查询签到表
    this.listSignin()
    this.finishTotal()
    this.undoneTotal()
    this.getJobList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})